/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {DeviceEventEmitter, Image, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native';

import Navigation from "../../../custom/Navigation";
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import WalletDetail from "./WalletDetail";
import WithdrawPage from "./WithdrawPage";
import I18n from "../../../res/language/i18n";
import IparNetwork, {getSynPaysSellerAuth, SynpaysTeken, SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import AlertDialog from "../../../custom/AlertDialog";
import VerifyPersonalPage from "../business/VerifyPersonalPage";
import UserInformationEdit from "../userInfo/UserInformationEdit";
import SendMoneyPage from "./SendMoneyPage";


export default class WalletPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            showDialog: false,
            balance: 0,
            currency: 0,
            userData: null,
            currency_code: '',
            selectAlertVisible: false,
        };
        this.country = null;
        this.iparNetwork = new IparNetwork();
    }

    componentWillUnmount() {
        this.iparNetwork = null;
    }

    componentDidMount() {
        CommonUtils.showLoading();

        CommonUtils.getAcyncInfo('getPv')
            .then((result) => {
                this.setState({
                    currency_code: JSON.parse(result).currency_code
                });
            });


        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                let parse = JSON.parse(result);
                this.setState({
                    userData: parse,
                });
                this.status = parse.status;
                this.userID = parse.main_user_id;
                this.country = parse.country;
                this.getBalanceInfo(parse.main_user_id);
            })
    }

    /*获取Synpays金额*/
    getBalanceInfo(userId) {
        this.iparNetwork.getRequest(SERVER_TYPE.adminIpar + 'Wallet?', 'UserID=' + userId, SynpaysTeken)
            .then((result) => {
                CommonUtils.dismissLoading();

                console.log(result);
                if (result.code === 200) {
                    let data = result.data.Balance;
                    this.setState({
                        balance: data.Balance,
                        currency: data.Currency,
                    })
                } else {
                    DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error);
                DeviceEventEmitter.emit('toast', I18n.t('default.fail'))
            })
    }

    render() {
        let userInfo = this.state.userData;
        let isNotNull = userInfo && userInfo.first_name && userInfo.last_name && userInfo.id_number;

        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                    rightButtonIcon={require('../../../res/images/ic_detel.png')}
                    onClickRightBtn={() => {
                        this.props.navigator.push({
                            component: WalletDetail,
                            params: {
                                getPv: this.state.currency_code,
                            }
                        })
                    }}
                />
                <AlertDialog
                    requestClose={() => {
                        this.setState({showDialog: false})
                    }}
                    visible={this.state.showDialog}
                    contentTv={I18n.t('default.verifyYourInfo')}
                    leftBtnOnclick={() => {
                        this.props.navigator.push({
                            component: UserInformationEdit,
                            params: {
                                userData: userInfo,
                                callback: (result) => {
                                    this.setState({userData: result});
                                    CommonUtils.saveUserInfo(result)
                                },
                            }
                        });
                        this.setState({showDialog: false})
                    }}

                />


                <AlertDialog
                    contentTv={I18n.t('default.selectWithdrawalType')}
                    leftBtnOnclick={() => {
                        this.starWithdrawal(0)
                    }}
                    rightBtnOnclick={() => {
                        this.starWithdrawal(1)
                    }}
                    leftSts={I18n.t('default.shop')}
                    rightSts={I18n.t('default.bankCard')}
                    visible={this.state.selectAlertVisible}
                    requestClose={() => this.setState({
                        selectAlertVisible: false
                    })}/>


                <View style={{padding: 16, height: '100%'}}>

                    {ViewUtils.getTitleView(I18n.t('default.myWallet'), I18n.t('default.availableBalance'))}

                    <Text
                        style={[styles.walletAmountTv, StyleUtils.smallFont]}>{this.state.balance + this.state.currency}</Text>
                    {ViewUtils.getButton(I18n.t('default.withdraw'), () => {
                        if (isNotNull) {
                            if (this.state.balance <= 0) {
                                DeviceEventEmitter.emit('toast', I18n.t('default.deficiency'))
                            } else {
                                // this.setState({selectAlertVisible: true})
                                this.starWithdrawal(0)
                            }
                        } else {
                            this.setState({showDialog: true})
                        }

                    }, {marginTop: 30})}

                    {ViewUtils.getButton(I18n.t('default.recharge'), () => {
                        if (isNotNull) {
                            if (this.state.balance <= 0) {
                                DeviceEventEmitter.emit('toast', I18n.t('default.deficiency'))
                            } else {
                                this.starWithdrawal(2);
                            }
                        } else {
                            this.setState({showDialog: true})
                        }
                    }, {marginTop: 16})}

                    {ViewUtils.getButton(I18n.t('pay.transfer'), () => {
                        if (this.state.balance <= 0) {
                            DeviceEventEmitter.emit('toast', I18n.t('default.deficiency'))
                        } else {
                            this.props.navigator.push({
                                component: SendMoneyPage,
                                params: {
                                    balance: this.state.balance + this.state.currency,
                                    callBack: () => {
                                        this.getBalanceInfo(this.state.userData.main_user_id)
                                    }
                                }
                            })
                        }
                    }, {marginTop: 16, backgroundColor: 'white', borderWidth: 1}, {color: 'black'})}
                    <View style={styles.commonTvBox}>
                        <Text style={[styles.commonTv, StyleUtils.smallFont]}>{I18n.t('default.commonQand')}</Text>
                    </View>
                </View>
            </View>)


    }


    /**
     * type ==> 0  实体店; 1 银行卡; 2 充值;
     * @param type
     */
    starWithdrawal(type) {
        this.setState({selectAlertVisible: false},
            this.props.navigator.push({
                component: WithdrawPage,
                params: {
                    balance: this.state.balance,
                    getPv: this.state.currency,
                    type: type,
                    callback: ((d) => {
                        if (d) {
                            CommonUtils.showLoading();
                            this.getBalanceInfo(this.userID)
                        }
                    })
                }
            })
        )

    }

}

const styles = StyleSheet.create({
    walletAmountTv: {
        textAlign: 'center',
        fontSize: 30,
        color: 'black'
    },
    commonTvBox: {
        flex: 1,
        marginBottom: '35%',
        justifyContent: 'flex-end'
    },
    commonTv: {
        textAlign: 'center',
        fontSize: 16
    }
});

